package GUILag;

import ControllerLag.LockerCTR;
import javax.swing.table.DefaultTableModel;
import ControllerLag.LockerCustomerCTR;
import ModelLag.Locker;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
 * Udlejning af skabe GUI.
 * @author DM75 Gruppe 3.
 * @version 22-12-2011.
 */
public class LockerGUI extends javax.swing.JFrame {
    private LockerCustomerCTR lockerCCTR;
    private LockerCTR lockerCTR;
    private boolean debug = false;
    private static LockerGUI _instance; // singleton
    
    /** Creates new form LockerGUI */
    private LockerGUI() 
    {
        initComponents();
        lockerCCTR = new LockerCustomerCTR();
        lockerCTR = new LockerCTR();
        //updateTable();
        
        //Højreklik i tabel.
        lockerTable.addMouseListener( new MouseAdapter()
        {
            public void mouseReleased(MouseEvent e)
            {
                if (e.isPopupTrigger())
                {
                    JTable source = (JTable)e.getSource();
                    int row = source.rowAtPoint( e.getPoint() );
                    int column = source.columnAtPoint( e.getPoint() );

                    if (! source.isRowSelected(row))
                        source.changeSelection(row, column, false, false);
                    
                    if(lockerTable.getValueAt(source.getSelectedRow(), 6) == null)
                    {
                        deleteMenuItem.setEnabled(false);
                        updCusMenuItem.setEnabled(false);
                        updKeysMenuItem.setEnabled(false);
                    }
                    else
                    {
                        deleteMenuItem.setEnabled(true);
                        updCusMenuItem.setEnabled(true);
                        updKeysMenuItem.setEnabled(true);
                    }
                    jPopupMenu1.show(e.getComponent(), e.getX(), e.getY());         
                }
            }
        });
    }
    
    // Kaldes af den klasse der ønsker en instans af dette frame.
    public static LockerGUI getInstance()
    {
        if(_instance == null)
        {
            _instance = new LockerGUI();
        }
        return _instance;
    }
    
    protected DefaultTableModel getModel()
    {
        return (DefaultTableModel) lockerTable.getModel();
    }
    
    // Opdatere tabellen med skabe.
    public void updateTable()
    {
        getModel().setRowCount(0);
        // Henter de skabe der ikke er udlejet.
        for(Locker lockerObj : lockerCCTR.getFreeLockers())
        {
            
            int ID = lockerObj.getLockerID();
            String status = "Fri";
            String lockerType = lockerObj.getLockerType();
            Double depositum = lockerObj.getDepositum();
            Double priceYear = lockerObj.getPricePrYear();
            int noOfKeys = lockerObj.getAmountOfKeys();
            Object[] data = {ID, status, lockerType, depositum, priceYear, noOfKeys, null, null};
            
            getModel().addRow(data);
        }
        // Henter de skabe der er udlejet.
        for(Locker lockerObj : lockerCCTR.getAllRentetLockers())
        {
            int ID = lockerObj.getLockerID();
            String status = "Optaget";
            String lockerType = lockerObj.getLockerType();
            Double depositum = lockerObj.getDepositum();
            Double priceYear = lockerObj.getPricePrYear();
            int noOfKeys = lockerObj.getAmountOfKeys();
            String name = lockerObj.getCustomer().getfName() + " " + lockerObj.getCustomer().getlName();
            String phoneNo = lockerObj.getCustomer().getPhoneNo();
            
            Object[] data = {ID, status, lockerType, depositum, priceYear, noOfKeys, name, phoneNo};
            
            getModel().addRow(data);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        deleteMenuItem = new javax.swing.JMenuItem();
        updCusMenuItem = new javax.swing.JMenuItem();
        updKeysMenuItem = new javax.swing.JMenuItem();
        lockerPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lockerTable = new javax.swing.JTable();
        closeButton = new javax.swing.JButton();

        deleteMenuItem.setText("Fjern kunde fra skab");
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(deleteMenuItem);

        updCusMenuItem.setText("Ændre kunde");
        updCusMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updCusMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(updCusMenuItem);

        updKeysMenuItem.setText("Opdater antal nøgler");
        updKeysMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updKeysMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(updKeysMenuItem);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Skabsudlejning");

        lockerTable.setAutoCreateRowSorter(true);
        lockerTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Status", "Størrelse", "Depositum", "Pris pr. år", "Udlev. nøgler", "Navn", "Telefon nr."
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        lockerTable.getTableHeader().setReorderingAllowed(false);
        lockerTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lockerTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lockerTable);
        lockerTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        lockerTable.getColumnModel().getColumn(1).setPreferredWidth(80);
        lockerTable.getColumnModel().getColumn(2).setPreferredWidth(80);
        lockerTable.getColumnModel().getColumn(3).setPreferredWidth(80);
        lockerTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        lockerTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        lockerTable.getColumnModel().getColumn(6).setPreferredWidth(200);
        lockerTable.getColumnModel().getColumn(7).setPreferredWidth(100);

        closeButton.setText("Luk");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout lockerPanelLayout = new javax.swing.GroupLayout(lockerPanel);
        lockerPanel.setLayout(lockerPanelLayout);
        lockerPanelLayout.setHorizontalGroup(
            lockerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(lockerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(lockerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(closeButton)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 717, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        lockerPanelLayout.setVerticalGroup(
            lockerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(lockerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(closeButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lockerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lockerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed
        int input = JOptionPane.showConfirmDialog(this, "Er du sikker på at du vil stoppe udlejningen?", "Bekræft stopning af udlejning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if(input == JOptionPane.OK_OPTION)
        {
            int selectedRow = lockerTable.getSelectedRow();
            int lockerID = (Integer) lockerTable.getValueAt(selectedRow, 0);
            int rc = lockerCCTR.deleteARent(lockerID);
        
            if(rc == 1)
            {
                int rowInModel = lockerTable.convertRowIndexToModel(selectedRow);
                getModel().setValueAt("Fri", rowInModel, 1);
                getModel().setValueAt(0, rowInModel, 5);
                getModel().setValueAt(null, rowInModel, 6);
                getModel().setValueAt(null, rowInModel, 7);
                JOptionPane.showMessageDialog(this, "Kunden er nu fjernet fra skabet.", "Udlejning stoppet", JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog(this, "En fejl er opstået.", "Fjernelse af kunde mislykkedes", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_deleteMenuItemActionPerformed

    protected int getSelectedLockerID()
    {
        return (Integer)lockerTable.getValueAt(lockerTable.getSelectedRow(), 0);
    }
    protected String getSelectedLockerType()
    {
        return (String)lockerTable.getValueAt(lockerTable.getSelectedRow(), 2);
    }
    protected String getSelectedCustomer()
    {
        return (String)lockerTable.getValueAt(lockerTable.getSelectedRow(), 6);
    }
    
    protected void updateRow(String status, int noOfKeys, String name, String phoneNo)
    {
        int selectedRow = lockerTable.getSelectedRow();
        lockerTable.setValueAt(status, selectedRow, 1);
        lockerTable.setValueAt(noOfKeys, selectedRow, 5);
        lockerTable.setValueAt(name, selectedRow, 6);
        lockerTable.setValueAt(phoneNo, selectedRow, 7);
    }
    
    protected void updateCustomer(String name, String phoneNo)
    {
        int selectedRow = lockerTable.getSelectedRow();
        lockerTable.setValueAt(name, selectedRow, 6);
        lockerTable.setValueAt(phoneNo, selectedRow, 7);
    }

    private void lockerTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lockerTableMouseClicked
        int selectedRow = lockerTable.getSelectedRow();
        String status = (String) lockerTable.getValueAt(selectedRow, 1);

        if(evt.getClickCount() == 2 && !status.equals("Optaget"))
        {
            LockerRentLocker rentLocker = new LockerRentLocker(this);
            rentLocker.setVisible(true);
            setGUIDisabled();
        }
        else if (evt.getClickCount() == 2 && status.equals("Optaget"))
        {
            JOptionPane.showMessageDialog(this, "Dette skab er optaget. Vælg et ledigt skab", "Skabet er optaget", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_lockerTableMouseClicked

    private void updCusMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updCusMenuItemActionPerformed
        LockerChangeCustomer lCCustomer = new LockerChangeCustomer(this);
        lCCustomer.setVisible(true);
        setGUIDisabled();
    }//GEN-LAST:event_updCusMenuItemActionPerformed

    private void updKeysMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updKeysMenuItemActionPerformed
        int selectedRow = lockerTable.getSelectedRow();
        String str = JOptionPane.showInputDialog(this,"Indtast nyt antal udleverede nøgler:");
        if(str != null)
        {
            try
            {
                int noOfKeys = Integer.parseInt(str);
                int lockerID = (Integer)lockerTable.getValueAt(selectedRow, 0);
                Locker lockerObj = lockerCTR.findLocker(lockerID);
                lockerObj.setAmountOfKeys(noOfKeys);

                int rc =lockerCTR.updateLocker(lockerObj.getLockerID(), lockerObj.getAvailable(), lockerObj.getDepositum() , lockerObj.getPricePrYear(), noOfKeys, lockerObj.getLockerType());
                if(rc == 1)
                {
                    int rowInModel = lockerTable.convertRowIndexToModel(selectedRow);
                    getModel().setValueAt(noOfKeys, rowInModel, 5);
                    JOptionPane.showMessageDialog(this, "Opdatering lykkedes.", "Opdatering lykkedes", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            catch(Exception e)
            {
                if(debug)
                {
                    System.out.println(e.getMessage());
                }
                JOptionPane.showMessageDialog(this, "Indtast et tal.", "Kun tal godkendes", JOptionPane.ERROR_MESSAGE);
                //Kalder sig selv.
                updKeysMenuItemActionPerformed(evt);
            }
        }
    }//GEN-LAST:event_updKeysMenuItemActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    protected void setGUIDisabled()
    {
        this.setEnabled(false);
    }
    
    protected void setGUIEnabled()
    {
        this.setEnabled(true);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel lockerPanel;
    private javax.swing.JTable lockerTable;
    private javax.swing.JMenuItem updCusMenuItem;
    private javax.swing.JMenuItem updKeysMenuItem;
    // End of variables declaration//GEN-END:variables
}
